package org.xhy.hrm.service.impl;

import com.alibaba.fastjson.JSON;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.transaction.annotation.Transactional;
import org.xhy.hrm.asserts.GlobleAssert;
import org.xhy.hrm.config.MQConfig;
import org.xhy.hrm.constants.MQConstants;
import org.xhy.hrm.context.LoginUserContext;
import org.xhy.hrm.doc.CourseDoc;
import org.xhy.hrm.domain.*;
import org.xhy.hrm.dto.CourseDto;
import org.xhy.hrm.dto.EmailSendDto;
import org.xhy.hrm.dto.SmsSendDto;
import org.xhy.hrm.dto.StationSendDto;
import org.xhy.hrm.feign.CourseESFeign;
import org.xhy.hrm.mapper.CourseDetailMapper;
import org.xhy.hrm.mapper.CourseMapper;
import org.xhy.hrm.mapper.CourseMarketMapper;
import org.xhy.hrm.mapper.CourseTypeMapper;
import org.xhy.hrm.service.ICourseService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.xhy.hrm.util.AjaxResult;

import java.util.Arrays;
import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xhy
 * @since 2021-09-14
 */
@Service
@Transactional
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements ICourseService {

    @Autowired
    private CourseDetailMapper courseDetailMapper;

    @Autowired
    private CourseMarketMapper courseMarketMapper;

    @Autowired
    private CourseTypeMapper courseTypeMapper;

    @Autowired
    private CourseESFeign courseESFeign;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     *
     * @param dto 临时接收三个参数
     *            private Course course;   课程
     *            private CourseDetail courseDetail;    课程详情
     *            private CourseMarket courseMarket;    课程营销
     */
    @Override
    public void save(CourseDto dto) {

        ////SecurityContextHolder.getContext拿到上下文,拿到loginUser
        LoginUser loginUser = LoginUserContext.getLoginUser();

        Course course = dto.getCourse();
        CourseDetail courseDetail = dto.getCourseDetail();
        CourseMarket courseMarket = dto.getCourseMarket();

        //简单验证
        GlobleAssert.hasText(course.getName(),"名字不能为空");

        //保存课程，先设置死未传的参数
        course.setTenantId(loginUser.getTenantId());
        course.setTenantName(loginUser.getCompanyName());
        course.setUserId(loginUser.getId());
        course.setUserName(loginUser.getUsername());
        //保存
        baseMapper.insert(course);

        //保存详情 1对1关联的表将主键id关联
        courseDetail.setId(course.getId());
        courseDetailMapper.insert(courseDetail);

        //保存营销 1对1关联的表将主键id关联
        courseMarket.setId(course.getId());
        courseMarketMapper.insert(courseMarket);

        //课程分类中的课程数量加1 将课程表中的CourseTypeId取出来 课程类型查询
        CourseType courseType = courseTypeMapper.selectById(course.getCourseTypeId());
        courseType.setTotalCount(courseType.getTotalCount()+1);
        courseTypeMapper.insert(courseType);
    }


    /**
     * 课程上线
     * 1.通过id查询课程
     * 2.判断非空、未上线
     * 3.修改状态为上线
     * 4.将课程放到ES中
     * @param id
     */
    @Override
    public void onLineCourse(Long id) {
        //通过id查询课程
        GlobleAssert.isNotNull(id,"无效ID");
        //判断非空、未上线
        Course course = baseMapper.selectById(id);
        System.out.println(course.toString());
        GlobleAssert.isNotNull(course,"无效课程");
        GlobleAssert.isEquals(course.getStatus(),Course.STATE_OFFLINE,"此课程已经上线");
        //修改状态为上线
        course.setStatus(Course.STATE_ONLINE);
        baseMapper.updateById(course);
        //将课程放到ES中
        //还要保存营销中的数据
        CourseMarket courseMarket = courseMarketMapper.selectById(course);
        //创建一个doc对象
        CourseDoc courseDoc = new CourseDoc();
        //工具类复制参数
        BeanUtils.copyProperties(course,courseDoc);
        BeanUtils.copyProperties(courseMarket,courseDoc);
        //修改收费的字段
        courseDoc.setCharge(courseMarket.getCharge().intValue() == 1 ? "免费" : "收费");
        //设置上线时间
        courseDoc.setOnlineTime(new Date());
        //调用feign接口保存
        AjaxResult ajaxResult = courseESFeign.save(courseDoc);
        System.out.println(ajaxResult);
        //判断
        GlobleAssert.isTrue(ajaxResult.isSuccess(),ajaxResult.getMessage());

        //发送队列消息
        //短信的信息
        String content = "尊敬的用户你好，我们最新的课程【" + course.getName() + "】已经上线了！，<a href='https://www.baidu.com'>速度来看看！";
        SmsSendDto smsSendDto = new SmsSendDto(content, Arrays.asList("123","456","789"),Arrays.asList(1l,2l,3l));
        //发送消息
        rabbitTemplate.convertAndSend(MQConstants.NAME_EXCHANGE_HRM_TOPIC,"course.sms",smsSendDto);

        //邮件的信息
        String emailContent = "尊敬的用户你好，我们最新的课程【" + course.getName() + "】已经上线了！，<a href='https://www.baidu.com'>速度来看看！";
        EmailSendDto emailSendDto = new EmailSendDto("课程",emailContent,Arrays.asList("123@qq.com","456@qq.com","789@qq.com"),Arrays.asList(1l,2l,3l));
        //发送消息
        rabbitTemplate.convertAndSend(MQConstants.NAME_EXCHANGE_HRM_TOPIC,"course.email",emailSendDto);

        //站内信的信息
        String staContent = "尊敬的用户你好，我们最新的课程【" + course.getName() + "】已经上线了！，<a href='https://www.baidu.com'>速度来看看！";
        StationSendDto stationSendDto = new StationSendDto(1,"课程消息",staContent,Arrays.asList(1l,2l,3l));
        //发送消息
        rabbitTemplate.convertAndSend(MQConstants.NAME_EXCHANGE_HRM_TOPIC,"course.station",stationSendDto);
    }

    @Override
    public void offLineCourse(Long id) {
        //通过id查询课程
        GlobleAssert.isNotNull(id,"无效ID");
        //判断非空、是否以上线
        Course course = baseMapper.selectById(id);
        GlobleAssert.isNotNull(course,"无效课程");
        GlobleAssert.isEquals(course.getStatus(),Course.STATE_ONLINE,"此课程已经下线");
        //修改状态为下线
        course.setStatus(Course.STATE_OFFLINE);
        baseMapper.updateById(course);
        AjaxResult ajaxResult = courseESFeign.deleteById(course.getId());
        //判断
        GlobleAssert.isTrue(ajaxResult.isSuccess(),ajaxResult.getMessage());
    }
}
